package com.lagou.sqlSession;

import com.lagou.com.SqlType;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;

import java.lang.reflect.*;
import java.util.List;

/**
 * description DefaultSqlSession
 * author wy
 * date 2021-04-07 20:12
 **/
public class DefaultSqlSession implements SqlSession
{
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration)
    {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception
    {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<Object> list = simpleExecutor.query(configuration, mappedStatement, params);
        return (List<E>) list;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception
    {
        List<Object> list = selectList(statementId, params);
        if (list.size() == 1)
        {
            return (T) list.get(0);
        }else {
            throw new RuntimeException("查询结果为空或过多。");
        }
    }

    @Override
    public int insert(String statementId, Object... params) throws Exception
    {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        int count = simpleExecutor.insert(configuration, mappedStatement, params);
        return count;
    }

    @Override
    public int update(String statementId, Object... params) throws Exception
    {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        int count = simpleExecutor.update(configuration, mappedStatement, params);
        return count;
    }

    @Override
    public int delete(String statementId, Object... params) throws Exception
    {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        int count = simpleExecutor.delete(configuration, mappedStatement, params);
        return count;
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass)
    {
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler()
        {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
            {
                // 底层去执行JDBC代码,根据不同情况调用selectList或者selectOne
                // 准备参数 1：statementId :sql语句的唯一标识：namespace.id= 接口全限定名.方法名
                // 方法名
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = className + "." + methodName;

                MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
                SqlType sqlType = mappedStatement.getSqlType();
                if (SqlType.SELECT.equals(sqlType))
                {
                    // 获取被调用方法的返回值类型
                    Type returnType = method.getGenericReturnType();
                    // 判断是否进行了 泛型类型参数化
                    if (returnType instanceof ParameterizedType)
                    {
                        List<Object> objects = selectList(statementId, args);
                        return objects;
                    }
                    return selectOne(statementId, args);
                }
                else if (SqlType.INSERT.equals(sqlType))
                {
                    return insert(statementId, args);
                }
                else if (SqlType.UPDATE.equals(sqlType))
                {
                    return update(statementId, args);
                }
                else if (SqlType.DELETE.equals(sqlType))
                {
                    return delete(statementId, args);
                }

                throw new Exception("不支持此方法");
            }
        });
        return (T) proxyInstance;
    }


}
